<template>
  <div>
    <el-dialog
      :title="handleType == 'edit' ? '编辑活动' : '新增活动'"
      width="1200px"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <div class="dialogBody">
        <el-form
          :model="params"
          :rules="rules"
          inline
          ref="ruleForm"
          label-position="left"
          label-width="130px"
          size="small"
        >
          <div class="flexItem">
            <el-form-item label="活动类型：" prop="type">
              <el-select
                v-model="params.type"
                placeholder="请选择活动类型"
                @change="onTypeSelect"
                :disabled="drReadonly"
              >
                <el-option
                  v-show="item.is_add == 1"
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in typeList"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="活动起止时间：" prop="time">
              <el-date-picker
                v-model="params.time"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="~"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @input="$forceUpdate()"
                @change="activityTime"
              >
              </el-date-picker>
            </el-form-item>
          </div>
          <div class="flexItem">
            <el-form-item label="活动标题：" prop="name">
              <el-input v-model="params.name"></el-input>
            </el-form-item>
            <el-form-item label="报名起止时间：" prop="time1">
              <el-date-picker
                v-model="params.time1"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="~"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @input="$forceUpdate()"
                @change="applyTime"
              >
              </el-date-picker>
            </el-form-item>
          </div>
          <div class="flexItem">
            <el-form-item label="活动地址：" prop="address">
              <el-input v-model="params.address"></el-input>
            </el-form-item>
            <el-form-item label="性别限制：" prop="sex_limit">
              <el-select v-model="params.sex_limit" placeholder="">
                <el-option label="不限" value="3"> </el-option>
                <el-option label="男" value="1"> </el-option>
                <el-option label="女" value="2"> </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="flexItem">
            <el-form-item label="人数限制：" prop="person_num_limit">
              <el-input
                oninput="value=value.replace(/[^0-9]/g,'')"
                v-model="params.person_num_limit"
                @blur="params.person_num_limit = $event.target.value"
              ></el-input>
            </el-form-item>
            <el-form-item label="年龄限制：" prop="age_limit">
              <el-select v-model="params.age_limit" placeholder="">
                <el-option label="不限" value="5"> </el-option>
                <el-option label="0-17岁" value="1"> </el-option>
                <el-option label="18-30岁" value="2"> </el-option>
                <el-option label="30-60岁" value="3"> </el-option>
                <el-option label="60+岁" value="4"> </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="flexItem">
            <el-form-item label="积分类型：" prop="integralType">
              <el-checkbox-group v-model="params.integralType">
                <el-checkbox label="1">系统积分</el-checkbox>
                <el-checkbox label="2" v-if="!drReadonly">荣誉积分</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item
              label="系统积分类型："
              prop="point_type"
              v-if="params.integralType.includes('1')"
            >
              <el-select
                :disabled="drReadonly"
                v-model="params.point_type"
                placeholder=""
              >
                <el-option label="获得" value="1"> </el-option>
                <el-option label="消耗" value="2"> </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="flexItem">
            <el-form-item
              label="积分数/人："
              prop="point_num"
              v-if="params.integralType.includes('1')"
            >
              <el-input
                oninput="value=value.replace(/[^0-9]/g,'')"
                v-model="params.point_num"
                @blur="params.point_num = $event.target.value"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="选择社团："
              prop="clubs_id"
              v-if="params.type == 3"
            >
              <el-select v-model="params.clubs_id" placeholder="">
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in clubList"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="活动发起人：" prop="originator" v-else>
              <!-- <el-input v-model="params.originator"></el-input> -->
              <div class="dialogBody">
                <div class="searchBox">
                  <el-autocomplete
                    :disabled="drReadonly"
                    popper-class="my-autocomplete"
                    v-model="params.originator"
                    :fetch-suggestions="querySearchAsync"
                    placeholder="请输入"
                    @select="handleSelect"
                  >
                    <template slot-scope="{ item }">
                      <div v-if="item.id == -1">无匹配结果</div>
                      <div v-else>
                        <div class="name">{{ item.userName }}</div>
                      </div>
                    </template>
                  </el-autocomplete>
                </div>
              </div>
            </el-form-item>
          </div>
          <div class="flexItem">
            <el-form-item
              label="荣誉积分数/人："
              prop="honor_point_num"
              v-if="params.integralType.includes('2')"
            >
              <el-input
                oninput="value=value.replace(/[^\d]/g, '').replace(/(\d*)(\.?)(\d*).*/, '$1')"
                v-model="params.honor_point_num"
                @blur="params.honor_point_num = $event.target.value"
              ></el-input>
            </el-form-item>
          </div>
          <div class="flexItem">
            <el-form-item label="联系电话：" prop="originator_tel">
              <el-input
                :disabled="drReadonly"
                oninput="value=value.replace(/[^\d]/g, '').replace(/(\d*)(\.?)(\d*).*/, '$1')"
                v-model="params.originator_tel"
                @blur="params.originator_tel = $event.target.value"
              ></el-input>
            </el-form-item>
          </div>
          <el-form-item label="活动内容：" prop="content">
            <el-upload
              v-show="false"
              class="avatar-uploader-img"
              :action="action"
              :show-file-list="false"
              :on-success="uploadImgSuccess"
              :before-upload="beforeUploadImg"
              :on-error="uploadImgError"
              accept=".jpeg,.jpg,.png"
              :data="{ pathName: '' }"
            />
            <quill-editor
              ref="myQuillEditor"
              v-model="params.content"
              class="editor"
              :options="editorOption"
            />
          </el-form-item>
          <el-form-item label="温馨提示：">
            <el-input
              style="width: 920px"
              type="textarea"
              v-model="params.remarks"
              :rows="4"
            ></el-input>
          </el-form-item>
          <div class="flexItem">
            <el-form-item label="活动封面：" prop="cover">
              <UploadPhoto
                @onSuccess="onSuccess"
                :fileList="params.cover"
              ></UploadPhoto>
            </el-form-item>
            <el-form-item label="活动详情页：" prop="detail_pic">
              <UploadPhoto
                @onSuccess="onSuccess2"
                :fileList="params.detail_pic"
              ></UploadPhoto>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button size="small" type="primary" @click="onSubmit('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Quill from "quill";
import ImageResize from "quill-image-resize-module";
Quill.register("modules/imageResize", ImageResize);
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  ["blockquote", "code-block"], // 引用  代码块
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
  [{ script: "sub" }, { script: "super" }], // 上标/下标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  // [{'direction': 'rtl'}],                         // 文本方向
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ font: [] }], // 字体种类
  [{ align: [] }], // 对齐方式
  ["clean"], // 清除文本格式
  // ['link', 'image', 'video'] // 链接、图片、视频
  ["link", "image"], // 链接、图片
];

import { userList } from "@/api/activity.js";
import { getActiveTypes, saveActive, activeDetail } from "@/api/activity.js";
import { clubList, clubDetail } from "@/api/club.js";
import UploadPhoto from "@/components/UploadPhoto.vue";
import resDomain from "@/utils/resDomain";
import uploadDomain from "@/utils/uploadDomain";

export default {
  name: "",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    add_Or_edit: {
      type: String,
      default: "add",
    },
    id: "",
  },
  data() {
    return {
      resDomain,
      editorOption: {
        // 编辑框操作事件
        theme: "snow", // or 'bubble'
        placeholder: "请在这里输入？",
        modules: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function (value) {
                // 上传图片
                if (value) {
                  document.querySelector(".avatar-uploader-img input").click(); // 触发input框选择文件
                } else {
                  this.quill.format("image", false);
                }
              },
              link: function (value) {
                // 添加链接
                if (value) {
                  var href = prompt("请输入url");
                  this.quill.format("link", href);
                } else {
                  this.quill.format("link", false);
                }
              },
            },
          },
          imageResize: {
            //放大缩小
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
        },
      },
      action: `${uploadDomain}backend/upload/upload`,

      typeList: {},
      clubList: [],
      params: {
        status: 1,
        name: "",
        type: "",
        time: [],
        time1: [],
        address: "",
        sex_limit: "3",
        person_num_limit: "",
        age_limit: "5",
        integralType: ["1"],
        point_type: "1",
        point_num: "",
        honor_point_num: "",
        clubs_id: "",
        originator: "",
        originator_tel: "",
        originator_uid: "",
        remarks: "",
        cover: [],
        detail_pic: [],
      },
      rules: {
        type: [
          { required: true, message: "请选择活动类型", trigger: "change" },
        ],
        time: [
          {
            required: true,
            message: "请选择活动起止时间",
            trigger: "change",
          },
        ],
        name: [{ required: true, message: "请输入活动标题", trigger: "blur" }],
        time1: [
          {
            required: true,
            message: "请选择报名起止时间",
            trigger: "change",
          },
        ],
        address: [
          { required: true, message: "请输入活动地址", trigger: "blur" },
        ],
        sex_limit: [
          { required: true, message: "请选择性别限制", trigger: "change" },
        ],
        person_num_limit: [
          { required: true, message: "请输入人数限制", trigger: "blur" },
        ],
        age_limit: [
          { required: true, message: "请选择年龄限制", trigger: "change" },
        ],
        integralType: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个积分类型",
            trigger: "change",
          },
        ],
        point_type: [
          { required: true, message: "请选择系统积分数量", trigger: "change" },
        ],
        point_num: [
          { required: true, message: "请输入积分数量", trigger: "blur" },
        ],
        honor_point_num: [
          { required: true, message: "请输入荣誉积分数量", trigger: "blur" },
        ],

        originator_tel: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "手机号码格式不正确",
            trigger: "blur",
          },
        ],
        clubs_id: [
          { required: true, message: "请选择社团", trigger: "change" },
        ],
        originator: [
          { required: true, message: "请输入活动发起人", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请编辑活动内容", trigger: "blur" },
        ],
        cover: [
          { required: true, message: "请上传活动封面", trigger: "change" },
        ],
        detail_pic: [
          { required: true, message: "请上传活动详情页", trigger: "change" },
        ],
      },
      fileList1: [],
      fileList2: [],
      userInfo: {},
      handleType: this.add_Or_edit,
      drReadonly: false,
    };
  },

  components: {
    UploadPhoto,
  },

  computed: {},

  beforeMount() {},

  mounted() {
    if (this.id != "") {
      this.getDetails();
    }
    if (this.add_Or_edit == "edit") {
      this.handleType = "edit";
    } else {
      this.handleType = "add";
    }

    this.getActiveTypes();
    this.getClubList();
  },

  methods: {
    getDetails() {
      activeDetail({ id: this.id }).then((res) => {
        if (res.code == 200) {
          console.log(res.data, "++++++++++++++++++++++++++++++++++++++");
          if (res.data.type == 2) {
            this.drReadonly = true;
          }
          this.params = res.data;
          this.params.id = this.id;
          // this.params.integralType = [];
          let integralType = [];
          if (res.data.point_num > 0) {
            integralType.push("1");
            // this.params.integralType = integralType;
            this.$set(this.params, "integralType", integralType);
          }
          if (res.data.honor_point_num > 0) {
            integralType.push("2");
            // this.params.integralType = integralType;

            // this.params.integralType.push("2");
            this.$set(this.params, "integralType", integralType);
          }
          this.params.point_type = res.data.point_type.toString();
          this.params.age_limit = res.data.age_limit.toString();
          this.params.time = [res.data.begin_time, res.data.end_time];
          this.params.time1 = [
            res.data.sing_start_time,
            res.data.sing_end_time,
          ];
          this.params.cover = res.data.cover.split(",").map((item) => {
            return {
              name: "",
              url: item,
            };
          });
          this.params.detail_pic = res.data.detail_pic
            .split(",")
            .map((item) => {
              return {
                name: "",
                url: item,
              };
            });
        }
        console.log(this.params);
      });
    },
    //活动类型
    getActiveTypes() {
      getActiveTypes().then((res) => {
        if (res.code == 200) {
          this.typeList = res.data.list;
        }
      });
    },
    //社团列表
    getClubList() {
      clubList().then((res) => {
        if (res.code == 200) {
          this.clubList = res.data.list;
        }
      });
    },
    //获取上传的图片地址
    onSuccess(val) {
      console.log("remove", val);
      this.params.cover = val;
    },
    //获取上传的图片地址
    onSuccess2(val) {
      this.params.detail_pic = val;
    },
    onSubmit(formName) {
      //处理提交字段
      let params = {
        ...this.params,
        begin_time: this.params.time[0],
        end_time: this.params.time[1],
        sing_start_time: this.params.time1[0],
        sing_end_time: this.params.time1[1],
        cover: "",
        detail_pic: "",
      };
      if (this.params.cover.length > 0) {
        params.cover = this.params.cover.map((item) => item.url).join(",");
      }
      if (this.params.detail_pic.length > 0) {
        params.detail_pic = this.params.detail_pic
          .map((item) => item.url)
          .join(",");
      }
      if (this.params.time.length > 0 && this.params.time1.length > 0) {
        let activityStart = this.$moment(
          this.params.time[0],
          "YYYY-MM-DD HH:mm:ss"
        ).unix();
        let applyStart = this.$moment(
          this.params.time1[0],
          "YYYY-MM-DD HH:mm:ss"
        ).unix();
        let applyEnd = this.$moment(
          this.params.time1[1],
          "YYYY-MM-DD HH:mm:ss"
        ).unix();
        if (applyStart >= activityStart || applyEnd >= activityStart) {
          this.$message.warning("报名起止时间不能大于活动起止时间");
          return;
        }
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          saveActive(params).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: res.msg,
              });
              this.$emit("handleClose", true);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleClose() {
      this.$emit("handleClose");
    },

    // 富文本图片上传前
    beforeUploadImg(file) {
      if (file.size > 1048576 * 10) {
        this.$message.warning("请上传小于10MB的图片");
        return false;
      }
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      if (!isJPG) {
        this.$message.error("仅支持jpg、jpeg、png格式的图片！");
      } else {
        // 显示loading动画
        this.quillUpdate = true;
      }
      return isJPG;
    },

    // 上传成功
    uploadImgSuccess(res, file) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      const quill = this.$refs.myQuillEditor.quill;
      // console.log(res);
      // 如果上传成功
      if (res.code == "200" && res.data != null) {
        // 获取光标所在位置
        const length = quill.getSelection().index;
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(length, "image", resDomain + res.data);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        this.$message.error("图片插入失败");
      }
      // loading动画消失
      this.quillUpdate = false;
    },

    // 上传失败
    uploadImgError() {
      // loading动画消失
      this.quillUpdate = false;
      this.$message.error("图片插入失败");
    },
    async querySearchAsync(queryString, cb) {
      if (queryString && queryString.length > 0) {
        this.params.originator = queryString;
        try {
          const data = await userList({
            keywords: this.params.originator,
          }); //search定义在data里
          console.log(data);
          // 赋值给建议列表，渲染到页面
          let list = data.data;
          // 如果list.length等于0，则代表没有匹配到结果。手动给list添加一条提示信息
          if (list.length == "0") {
            list.push({
              id: "-1",
              value: "无匹配结果",
            });
            // 调用 callback 返回建议列表的数据
            cb(list);
          } else {
            // list = list.map((item) => {
            //   return {
            //     value: `${item.userName}`,
            //     id: `${item.id}`,
            //   };
            // });
            console.log(">>>list", list);
            // 调用 callback 返回建议列表的数据
            cb(list);
          }
        } catch (error) {
          console.log(error);
        }
      } else {
        cb([]);
      }
    },
    handleSelect(val) {
      // console.log(val, "<<<<<<valvalvalvlavlavlavl");
      this.params.originator = val.userName;
      this.params.originator_tel = val.mobile;
      this.params.originator_uid = val.id;
      this.userInfo = val;
    },
    onTypeSelect() {
      this.params.clubs_id = "";
      this.params.originator = "";
      this.params.originator_tel = "";
    },
    activityTime(val) {
      // 活动起止时间
      console.log(val);
      let activityStart = this.$moment(val[0], "YYYY-MM-DD HH:mm:ss").unix();
      if (this.params.time1.length > 0) {
        let applyStart = this.$moment(
          this.params.time1[0],
          "YYYY-MM-DD HH:mm:ss"
        ).unix();
        let applyEnd = this.$moment(
          this.params.time1[1],
          "YYYY-MM-DD HH:mm:ss"
        ).unix();
        if (applyStart >= activityStart || applyEnd >= activityStart) {
          this.$message.warning("报名起止时间不能大于活动起止时间");
          // this.params.time = [];
          // this.params.time1 = [];
        }
      }
      console.log(this.params.time1);
    },
    applyTime(val) {
      // 报名起止时间
      console.log(val);
      let applyStart = this.$moment(val[0], "YYYY-MM-DD HH:mm:ss").unix();
      let applyEnd = this.$moment(val[1], "YYYY-MM-DD HH:mm:ss").unix();
      if (this.params.time.length > 0) {
        let activityStart = this.$moment(
          this.params.time[0],
          "YYYY-MM-DD HH:mm:ss"
        ).unix();
        if (applyStart >= activityStart || applyEnd >= activityStart) {
          this.$message.warning("报名起止时间不能大于活动起止时间");
          // this.params.time = [];
          // this.params.time1 = [];
        }
      }
    },
  },

  watch: {
    "params.clubs_id": {
      handler(newVal, oldVal) {
        console.log(newVal, ">>>>");
        if (newVal != "") {
          clubDetail({ id: newVal }).then((res) => {
            if (res.code == 200) {
              this.params.originator_tel = res.data.mobile;
              this.params.clubs_id = res.data.id;
            }
          });
        }
      },
      deep: true,
    },
    // "params.type": {
    //   handler(newVal, oldVal) {
    //     if (newVal !== oldVal) {
    //       this.params.clubs_id = "";
    //       this.params.originator = "";
    //       this.params.originator_tel = "";
    //     }
    //   },
    //   deep: true,
    //   immediate: false,
    // },
  },
};
</script>
<style lang="scss" scoped>
.dialogBody {
  /deep/.flexItem {
    display: flex;
    justify-content: space-between;
    .el-form-item {
      flex: 1;
    }
    .el-input__inner {
      width: 200px;
    }
    .el-range-editor,
    .el-input__inner {
      width: 350px;
    }
  }
}

.quill-editor {
  margin-left: 130px;
  width: 80%;
}
// 给文本内容加高度，滚动条

.quill-editor /deep/ .ql-container {
  min-height: 220px;
}

.ql-container {
  min-height: 230px;
  width: 80%;
}
</style>
